package com.efounder.util;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

import androidx.appcompat.app.AlertDialog;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.forwechat.BaseApp;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.AppUtils;
import com.utilcode.util.ToastUtils;

import java.util.List;

import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * 设置页面相关方法的管理类
 *
 * @author wang
 */
public class CommonSettingManager {

    private Context context;

    public CommonSettingManager(Context context) {
        this.context = context;
    }

    /**
     * 跳转到应用详情页
     */
    public void checkGoogleStoreUpdate() {
        //这里对应的是谷歌商店，跳转别的商店改成对应的即可
        String googlePlay = "com.android.vending";
        Intent intent = getIntent(context);
        intent.setPackage(googlePlay);
        boolean b = isMarketAvailable(context, intent);
        if (!b) {
            try {
                context.startActivity(intent);
            } catch (Exception e) {
                ToastUtils.showShort(R.string.goto_google_play_fail);
                Log.e("tag", "有应用市场，但是跳转失败");
            }
        } else {
            ToastUtils.showShort(R.string.goto_google_play_fail);
            Log.e("tag", "手机当前没有应用市场");
        }
    }

    /**
     * 判断是否有应用市场
     *
     * @param context      上下文
     * @param marketIntent 跳转意图
     * @return 是否有应用市场true/false
     */
    private static boolean isMarketAvailable(Context context, Intent marketIntent) {
        List<ResolveInfo> localList = context.getPackageManager().queryIntentActivities(marketIntent, PackageManager.GET_RESOLVED_FILTER);
        return !((localList != null) && (localList.size() > 0));
    }

    /**
     * 获取跳转意图
     *
     * @param context 上下文
     * @return 意图
     */
    public static Intent getIntent(Context context) {
        StringBuilder localStringBuilder = new StringBuilder().append("market://details?id=");
        String str = context.getPackageName();
        localStringBuilder.append(str);
        Uri localUri = Uri.parse(localStringBuilder.toString());
        return new Intent("android.intent.action.VIEW", localUri);
    }

    /**
     * 弹出退出登录确认
     */
    public void showExitLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(ResStringUtil.getString(R.string.left_fragment_tip_logout));
        builder.setTitle(ResStringUtil.getString(R.string.common_text_hint));
        builder.setPositiveButton(ResStringUtil.getString(R.string.common_text_exit), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                logout();

            }
        });
        builder.setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });
        builder.create().show();
    }

    /**
     * 用户注销退出登录
     */
    private void logout() {
        startLogOut();
    }

    /**
     * 开始登出
     */
    public void startLogOut() {
        BaseApp.actManager.closeAllActivity();
//        ((Activity) context).finishAffinity();
        LogOutUtil.stopLocalIMService(context);
        //清空华为手机等外部的角标
        ShortcutBadger.applyCount(AppContext.getInstance(), 0);

        //延时500ms
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (EnvironmentVariable.getProperty("exitOrRelaunch", "exit").equals("exit")) {
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(0);
                    AppUtils.exitApp();
                } else {
                    AppUtils.relaunchApp();
                }
            }
        }, 800);
    }
}
